package com.probiz.estore.catalog.dao.impl;

import com.probiz.estore.catalog.dao.ContentCategoryDao;
import com.probiz.estore.catalog.model.ContentCategorySearchCriteria;
import com.probiz.estore.common.model.catalog.ContentCategory;
import com.probiz.estore.common.util.SearchUtil;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.util.StringUtil;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Dao implementation for ContentCategory.
 */
public class ContentCategoryDaoImpl extends BaseCategoryDaoImpl<ContentCategory> implements ContentCategoryDao {
    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.dao.ContentCategoryDao#getCategoryByCode(java.lang.String)
      */
    public ContentCategory getCategoryByCode(String categoryCode) {
        return (ContentCategory) this.findUnique("from ContentCategory c where c.categoryCode=?", categoryCode);
    }

    /*
    * (non-Javadoc)
    * @see com.probiz.estore.catalog.dao.ContentCategoryDao#searchByCriteria(com.probiz.estore.catalog.model.ContentCategorySearchCriteria, com.probiz.estore.core.search.SearchCriteria)
    */
    public List<ContentCategory> searchByCriteria(ContentCategorySearchCriteria contentCategorySearchCriteria, SearchCriteria searchCriteria) {
        StringBuffer hqlsb = new StringBuffer(100);
        List<Object> paramList = new ArrayList<Object>();
        //start:构建HQL语句
        hqlsb.append("from ContentCategory c where 1=1 ");
        if (StringUtils.isNotBlank(contentCategorySearchCriteria.getKeywords())) {
            String keywords = SearchUtil.getSqlQueryValue(contentCategorySearchCriteria.getKeywords());
            hqlsb.append(" and ");
            hqlsb.append("(c.categoryName like ? ");
            hqlsb.append(" or c.keywords like ? ");
            hqlsb.append(" or c.categoryContext like ? ");
            hqlsb.append(" or c.metaDescription like ? )");
            for (int i = 0; i < 4; i++) {
                paramList.add("%" + keywords + "%");
            }
        }
      //-begin:目录
        if (!ArrayUtils.isEmpty(contentCategorySearchCriteria.getCategoryPaths())) {
            hqlsb.append(" and (");
            for (int i = 0; i < contentCategorySearchCriteria.getCategoryPaths().length; i++) {
                hqlsb.append("c.categoryPath like ?");
                if (i < contentCategorySearchCriteria.getCategoryPaths().length - 1) hqlsb.append(" or ");
                paramList.add(contentCategorySearchCriteria.getCategoryPaths()[i] + "%");
            }
            hqlsb.append(" )");
        }
        if (StringUtils.isNotBlank(contentCategorySearchCriteria.getCategoryPath())) {
            hqlsb.append(" and (");
            hqlsb.append("c.categoryPath like ?");
            hqlsb.append(" )");
            paramList.add(contentCategorySearchCriteria.getCategoryPath() + "%");

        }
        
        if (StringUtils.isNotBlank(contentCategorySearchCriteria.getCategoryId())) {
        	hqlsb.append(" and (");
        	hqlsb.append("c.categoryId = ?");
        	hqlsb.append(" )");
        	paramList.add(new Integer(contentCategorySearchCriteria.getCategoryId()));
        	
        }
        //-end:目录
        if (StringUtils.isNotBlank(contentCategorySearchCriteria.getCategoryName())) {
            hqlsb.append(" and c.categoryName like ?");
            paramList.add("%" + contentCategorySearchCriteria.getCategoryName() + "%");
        }

        if (null != contentCategorySearchCriteria.getStatus()) {
            hqlsb.append(" and c.status = ?");
            paramList.add(contentCategorySearchCriteria.getStatus());
        }

        if (!ArrayUtils.isEmpty(contentCategorySearchCriteria.getCategoryTypes())) {
            String categoryTypeString = StringUtil.arrayToString(contentCategorySearchCriteria.getCategoryTypes(), ",");
            hqlsb.append(" and c.categoryType in (").append(categoryTypeString).append(")");
        }
        //end:构建HQL语句
        searchCriteria.setHql(hqlsb.toString());
        searchCriteria.removeParamValues();
        for (Object object : paramList) {

            searchCriteria.addParamValue(object);
        }
        return searchByCriteria(searchCriteria);
    }

    /*
    * (non-Javadoc)
    * @see com.probiz.estore.catalog.dao.ContentCategoryDao#getNavigationCategories(java.lang.Integer)
    */
    public List<ContentCategory> getNavigationCategories(Integer categoryId) {
        List<ContentCategory> navigationCategories = new ArrayList<ContentCategory>();
        ContentCategory contetCategory = this.getById(categoryId);
        if (contetCategory == null)
            return navigationCategories;
        String categoryPath = contetCategory.getCategoryPath();
        if (StringUtils.isNotEmpty(categoryPath)) {
            String categoryIds[] = categoryPath.split("\\.");
            for (int i = 1; i < categoryIds.length; i++) {
                ContentCategory parentContentCategory = this
                        .getById(Integer.parseInt(categoryIds[i]));
                navigationCategories.add(parentContentCategory);
            }
        }
        return navigationCategories;
    }
    /*
     * (non-Javadoc)
     * @see com.probiz.estore.catalog.dao.ContentCategoryDao#getSizeByCategoryCodeByNotCategoryId(java.lang.String, java.lang.Integer)
     */
    public Long getSizeByCategoryCodeByNotCategoryId(final String categoryCode,final Integer categoryId){
		Long size;
    	if(categoryId != null){
    		
    		size = (Long)getHibernateTemplate().executeWithNewSession(new HibernateCallback() {
    			public Object doInHibernate(Session session)
    					throws HibernateException, SQLException {
    				StringBuffer sb = new StringBuffer();
    				sb.append("select count(*) from ContentCategory cc where cc.categoryCode = ? and cc.categoryId != ?");
    				Query query = session.createQuery(sb.toString());
    				query.setString(0, categoryCode);
    				query.setInteger(1, categoryId);
    				Long rows =  (Long)query.uniqueResult();
    				return rows;
    			}

    		});
    	}else{
    		size = (Long)getHibernateTemplate().executeWithNewSession(new HibernateCallback() {
    			public Object doInHibernate(Session session)
    					throws HibernateException, SQLException {
    				StringBuffer sb = new StringBuffer();
    				sb.append("select count(*) from ContentCategory cc where cc.categoryCode = ?");
    				Query query = session.createQuery(sb.toString());
    				query.setString(0, categoryCode);
    				Long rows =  (Long)query.uniqueResult();
    				return rows;
    			}

    		});
    	}	
    	return size;
	}

}
